<?php

// +———————————————————————————————————
// | Created by Yunbao
// +———————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +———————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +———————————————————————————————————
// | Date: 2022-05-28
// +———————————————————————————————————

namespace App\Domain;

use App\Model\Login as Model_Login;

class Login {

    public function userLogin($user_login,$source) {
        
        $rs = array('code' => 0, 'msg' => '', 'info' => array());
        

        $where=[
            'user_login = ?'=>$user_login,
        ];
        
        $model = new Model_Login();
        $info = $model->userLogin($where);
        
        if(!$info){
            /* 注册 */
            $nickname='';
            $data=array(
                'user_login' => $user_login,
                'user_nickname' => $nickname,
                "source"=>$source,
                "mobile"=>$user_login,
            );
            $model = new Model_Login();
            $info = $model->userReg($data);		
        }
        
        
        $info=$this->handleInfo($info);
  
        return $info;

    }
   
    public function reg($user_login,$user_pass,$source) {
        
        $rs = array('code' => 0, 'msg' => \PhalApi\T('注册成功'), 'info' => array());
        /* 注册 */
        
        $data=array(
            'user_login' => $user_login,
            'user_pass' => $user_pass,
            'user_nickname' => $nickname,
            "source"=>$source,
            "user_email"=>$user_login,
        );
        $model = new Model_Login();
        $info = $model->userReg($data);
        
		$info=$this->handleInfo($info);
  
        return $info;
        
    }
    
    
    protected function handleInfo($info){
        $rs = array('code' => 0, 'msg' => \PhalApi\T('登录成功'), 'info' => array());
        
		if($info['user_status']=='0'){
			$rs['code'] = 1004;
            $rs['msg'] = \PhalApi\T('该账号已被禁用');
            return $rs;	
        }
		if($info['user_status']=='3'){
			
			$rs['code'] = 1005;
            $rs['msg'] = \PhalApi\T('该账号已注销');
            return $rs;	
		}
        
		unset($info['user_status']);
		
		$info['isreg']='0';
		if(!$info['last_login_time']){
			$info['isreg']='1';
		}
        unset($info['last_login_time']);

		$info=\App\handleUser($info);
        
        \App\delcache('userinfo_'.$info['id']);
        
        $model = new Model_Login();
        $token=md5(md5($info['id'].$info['user_nickname'].time()));
		$info['token']=$token;
		$model->updateToken($info['id'],$token);
        
        $usersig=\App\setSig($info['id']);
		$info['usersig']=$usersig;
        
        $rs['info'][0]=$info;
        return $rs;
    }

}
